package com.silences.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.silences.pojo.User;
import com.silences.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    //把UserService 注入进来
    @Resource
    private UserService userService;

    //列表查询接口
    @RequestMapping("/getUsers")
    @ResponseBody
    public JSONObject getUsers(String username, int pageIndex, int pageSize){

        return JSON.parseObject(JSON.toJSONString(
                userService.getUsers(username, pageIndex, pageSize)));
    }

    //单个数据接口
    @RequestMapping("/getUser")
    @ResponseBody
    public JSONObject getUser(int id){

        return JSON.parseObject(JSON.toJSONString(userService.getUser(id)));
    }

    //添加数据接口
    @RequestMapping("/addUser")
    @ResponseBody
    public JSONObject addUser(@RequestBody User user){

        return JSON.parseObject(JSON.toJSONString(userService.addUser(user)));
    }

    //修改数据接口
    @RequestMapping("/updateUser")
    @ResponseBody
    public JSONObject updateUser(@RequestBody User user){

        return JSON.parseObject(JSON.toJSONString(userService.updateUser(user)));
    }

    //删除数据接口
    @RequestMapping("/deleteUser")
    @ResponseBody
    public JSONObject deleteUser(@RequestBody Map<String,Object> map){

        return JSON.parseObject(JSON.toJSONString(userService.deleteUser(Integer.parseInt(map.get("id")+""))));
    }

    //删除数据接口
    @RequestMapping("/deleteUsers")
    @ResponseBody
    public JSONObject deleteUsers(@RequestBody Map<String,Object> map){
        String ids =map.get("ids")+"";
        String[] idArr= ids.substring(0,ids.length()-1).split(",");
        return JSON.parseObject(JSON.toJSONString(userService.deleteUsers(idArr)));
    }
}
